import random
import sys

from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QColor, QBrush
from PyQt5.QtWidgets import QDialog, QApplication, QHeaderView

from windowUI.testDetailUI import Ui_TestDetailDialog


class TestDetailWindow(QDialog, Ui_TestDetailDialog):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)
        # 设置数据层次结构，10行3列
        # status，item，remarks
        self.tableModel = QStandardItemModel(self)
        # 设置水平方向四个头标签文本内容
        self.tableModel.setHorizontalHeaderLabels(['状态', '事项', '备注'])
        self.tableModel.itemChanged.connect(self.itemChanged)
        # 实例化表格视图，设置模型为自定义的模型
        self.tableView.setModel(self.tableModel)
        # todo 优化1 表格填满窗口
        # 水平方向标签拓展剩下的窗口部分，填满表格
        # self.tableView.horizontalHeader().setStretchLastSection(True)
        # 水平方向，表格大小拓展到适当的尺寸
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.tableView.horizontalHeader().setSectionResizeMode(0, QHeaderView.Fixed)
        self.tableView.setColumnWidth(0, 40)
        # #TODO 优化3 删除当前选中的数据
        # indexs=self.tableView.selectionModel().selection().indexes()
        # print(indexs)
        # if len(indexs)>0:
        #     index=indexs[0]
        #     self.model.removeRows(index.row(),1)
        # {"data":XX,"type":0,}
        # type : 0-指令(直接发送)

    # type：0-增加，1-修改
    def RecvMainData(self, dictData):
        # {'status': random.choice([True, False]), "item": 'haha5', "remarks": '','type':0,}
        typeValue = dictData.get("type", 0)
        statusValue = dictData.get("status", 0)
        itemStr = dictData.get('item', None)
        # 接受Form1传过来的msg，保存到自己的变量里面。
        print('TestDetail 收到 来自主界面信息：{}，item：{}，type: {}'.format(statusValue, itemStr, typeValue))
        if not itemStr:
            return
        if typeValue == 1:
            self.EditDataFun(dictData)
            return None
            # print('换颜色')
        self.InsertDataFun(dictData)

    def itemChanged(self, item):
        print("index {},Item {!r} checkState: {}".format(item.row(), item.text(), item.checkState()))
        self.EditDataFun({'status': item.checkState(), "item": item.text(), "remarks": '', 'row': item.row()})

    def SearchRowFun(self, dictData: dict):
        print(self.tableModel.columnCount())
        print(self.tableModel.rowCount())
        rowCount = self.tableModel.rowCount()
        colInd = 1
        for rowInd in range(rowCount):
            if self.tableModel.index(rowInd, colInd).data() == dictData.get('item', ''):
                # print('-' * 5, rowInd)
                # print('+' * 5, self.tableModel.item(rowInd, 0).checkState())
                print('找到测试项', rowInd)
                return rowInd
        # print(rowInd, rowCount)
        print('没有此测试项')
        return -1

    def EditDataFun(self, dictData: dict):
        rowInd = dictData.get('row', -1)
        if rowInd < 0:
            rowInd = self.SearchRowFun(dictData)
        else:
            statusNew = False
            if dictData.get('status', 0) > 0:
                statusNew = True
            self.tableModel.item(rowInd, 0).setCheckState(Qt.Checked if statusNew else Qt.Unchecked)
            self.tableModel.item(rowInd, 0).setBackground(QBrush(QColor(Qt.green if statusNew else Qt.red)))
            return None
        if rowInd < 0:
            return None
        self.tableModel.item(rowInd, 0).setCheckState(Qt.Checked)
        self.tableModel.item(rowInd, 0).setBackground(QBrush(QColor(Qt.green)))

    def InsertDataFun(self, dictData: dict):
        # Todo 优化2 添加数据
        itemRow0 = QStandardItem()
        itemRow0.setCheckable(True)
        itemRow0.setCheckState(Qt.Unchecked)
        itemRow0.setBackground(QBrush(QColor(Qt.red)))
        if dictData.get('status', False):
            itemRow0.setCheckState(Qt.Checked)
            itemRow0.setBackground(QBrush(QColor(Qt.green)))
        itemRow1 = dictData.get('item', False)
        itemRow2 = dictData.get('remarks', False)
        self.tableModel.appendRow([
            QStandardItem(itemRow0),
            QStandardItem(itemRow1),
            QStandardItem(itemRow2),
        ])

        # for row in range(4):
        #     for column in range(3):
        #         item = QStandardItem('row %s,column %s' % (row, column))
        #         # 设置每个位置的文本值
        #         item.setCheckable(True)
        #         self.tableModel.setItem(row, column, item)
        #


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = TestDetailWindow()
    ui.show()
    for i in range(32):
        ui.InsertDataFun(
            {'status': random.choice([True, False]), "item": 'haha' + str(random.randint(0, 30)), "remarks": ''})
    ui.EditDataFun({'status': random.choice([True, False]), "item": 'haha5', "remarks": ''})
    sys.exit(app.exec_())
